#include "Bullet.h"

Bullet::~Bullet()
{
    if (getCollisionEntity() != nullptr)
    {
        getCollisionEntity()->setParent(nullptr);
        // delete getCollisionEntity();
        // setCollisionEntity(nullptr);
    }
}

void Bullet::setOwner(Entity *owner)
{
    this->owner = owner;
}

Entity *Bullet::getOwner()
{
    return owner;
}

void Bullet::setTarget(Entity *target)
{
    this->target = target;
}

Entity *Bullet::getTarget()
{
    return target;
}

void Bullet::update(real delta)
{
    real rad = so_atan2(trackingPosition.y - getPosition().y, trackingPosition.x - getPosition().x);
    IRotation::rotateTo(delta, rad * 180 / PI);
    IMotion::motion(delta, getFacing() * PI / 180);
    IMotion::update(delta);
    ICollision::getCollisionEntity()->updatePosition(getPosition());
    if (elapsed())
    {
        exit();
    }
}

Entity *Bullet::updateCollision(real delta)
{
    updateTrackingPosition();
    if (target == nullptr || target->isExited())
    {
        real r = (getCollisionEntity()->getAABB()->getWidth() / 2);
        if ((getPosition() - trackingPosition).length2() < r * r)
        {
            exit();
        }
        target = nullptr;
        return nullptr;
    }
    if (target->getCollisionEntity()->contact(getCollisionEntity()) != Vector2())
    {
        return target;
    }
    return nullptr;
}

void Bullet::updateTrackingPosition()
{
    if (tracking && target != nullptr && !target->isExited())
    {
        trackingPosition = target->getPosition() + trackingOffset;
    }
}

void Bullet::setAttack(real val)
{
    attack = val;
}

real Bullet::getAttack()
{
    return attack;
}

void Bullet::setErrorAngle(real val)
{
    errorAngle = val;
}

real Bullet::getErrorAngle()
{
    return errorAngle;
}

void Bullet::setTrackingOffset(Vector2 val)
{
    trackingOffset = val;
}

Vector2 Bullet::getTrackingOffset()
{
    return trackingOffset;
}
